<template>
    <div v-loading="pageLoading">
        <!-- 搜索 -->
        <div class="search-info">
            <Search @searchChange="searchList" @handleAdd="handleAdd" />
        </div>
        <BasicTable
            :columns="columns"
            :height="120"
            :table-data="tableData"
            :row-config="rowConfig"
            :table-loading="tableLoading"
            :page-info="pageInfo"
            @onChangePage="(pageInfo: any) => searchList(FormData, pageInfo)"
        >
            <template #screenType="{ row }">
                <div>{{ screenType[row.screenType] }}</div>
            </template>
            <template #mediaType="{ row }">
                <div>{{ mediaType[row.mediaType] }}</div>
            </template>
            <template #auditStatus="{ row }">
                <div class="flex-box align-center">
                    <div class="dot" :class="'dot-' + row.auditStatus"></div>
                    <div>{{ ['审核中', '通过', '拒绝'][row.auditStatus] }}</div>
                </div>
            </template>
            <template #time="{ row }">{{ row.time ? `${row.time}s` : '' }}</template>
        </BasicTable>

        <!-- 抽屉 -->
        <el-drawer
            v-if="drawer"
            v-model="drawer"
            :title="drawerTitle"
            direction="rtl"
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            custom-class="customer-drawer"
        >
            <BaseForm ref="baseForm" :type="drawerType" :detail="baseFormDetail" />
            <template #footer>
                <div v-if="drawerType !== '1'">
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" :loading="drawerloading" @click="submitForm">确认</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import BasicTable from '@/components/BasicTable.vue';
import Search from '../components/Search.vue';
import BaseForm from '../components/BaseForm.vue';
import { ElMessage } from 'element-plus';
import { TableData, FormData } from '../ModelDefines';
import { getCreativeList, addOrUpdate, getDetail } from '@/api/delivery/creativeManage';
import { screenType, mediaType } from '@/utils/config';

import { formatDate2 } from '@x-tech/fe-utils/dist/date';

const pageLoading = ref(false);
const router = useRouter();
const baseForm = ref<any>(null);
const baseFormDetail = ref<any>({});
const drawer = ref(false);
const drawerType = ref('0');
const drawerWidth = ref('640px');
const drawerloading = ref(false);
const drawerTitle = computed(() => {
    const titles = ['新建', '查看', '编辑'];
    return `${titles[drawerType.value]}创意`;
});

const tableLoading = ref(false);
const tableData = ref<TableData[]>([]);
const pageInfo = reactive({
    pageNum: 1,
    total: 0,
    pageSize: 10,
});

const columns = [
    { label: '创意名称', key: 'name', prop: { minWidth: '200px', fixed: 'left' } },
    { label: '投放主体', key: 'deliverySubject', prop: { minWidth: '245px' } },
    { label: '创意ID', key: 'id', prop: { minWidth: '110px' } },
    { label: '创意行业 ', key: 'industryCodeName', prop: { minWidth: '180px' } },
    { label: '媒体类型', key: 'mediaType', prop: { minWidth: '120px' }, render: true },
    { label: '屏幕类型', key: 'screenType', prop: { minWidth: '120px' }, render: true },
    { label: '创意时长', key: 'time', prop: { minWidth: '130px' }, render: true },
    { label: '创意状态', key: 'auditStatus', prop: { minWidth: '150px' }, render: true },
    { label: '创意有效期', key: 'expireTime', prop: { minWidth: '200px' } },
];

const getDetailInfo = (id: string, type: string) => {
    drawerType.value = type;
    pageLoading.value = true;

    return new Promise(async (reslove, reject) => {
        try {
            const data = await getDetail(id);
            reslove(data);
        } catch (error) {
            reject({});
        } finally {
            pageLoading.value = false;
        }
    });
};

const rowConfig = [
    {
        color: '#4D88FF',
        name: '查看',
        on: async ({ row }: { row: any }) => {
            baseFormDetail.value = await getDetailInfo(row.id, '1');
            drawer.value = true;
        },
    },
    {
        color: '#4D88FF',
        name: '编辑',
        on: async ({ row }: { row: any }) => {
            // baseFormDetail.value = await getDetailInfo(row.id, '2');
            router.push({
                name: 'editManage',
                params: {
                    id: row.id,
                },
            });
        },
        isPermission: ({ row }: { row: any }) => [2].includes(+row.auditStatus),
    },
];

const searchList = async (formData: any, pageObj: any) => {
    // 表单重置的时候 分页设置为1
    pageInfo.pageNum = pageObj?.pageNum ? pageObj?.pageNum : pageInfo.pageNum;
    pageInfo.pageSize = pageObj?.pageSize ? pageObj?.pageSize : pageInfo.pageSize;
    formData.expireTime ? (formData.expireTime = formatDate2(formData.expireTime, 'YYYY-MM-DD')) : '';
    const params = Object.assign(formData, {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
    });
    tableLoading.value = true;
    try {
        const data = await getCreativeList(params);
        tableData.value = data ? data.records : [];
        pageInfo.total = data ? data.total : 0;
    } finally {
        tableLoading.value = false;
    }
};

const handleAdd = () => {
    console.log('routes', router.getRoutes());
    router.push({
        name: 'addManage',
        query: {},
    });
};

const submitForm = () => {
    baseForm.value.formRef.validate(async (valid: boolean, fields: boolean) => {
        if (valid) {
            const formData = baseForm.value.form;
            // 梯内
            if (formData.mediaType === 1) {
                if (formData.screenType === 2) {
                    if (!formData.materialDtoList.length) {
                        ElMessage.warning('请选择素材');
                        return;
                    }
                } else if (formData.screenType === 1) {
                    if (!formData.materialDtoList.length || formData.materialDtoList.length !== 3) {
                        ElMessage.warning('联动需要上传三个素材');
                        return;
                    }
                }
            }
            // 梯外
            if (formData.mediaType === 2) {
                if (formData.screenType === 2) {
                    if (!formData.materialDtoList.length || formData.materialDtoList.length !== 2) {
                        ElMessage.warning('上屏需要上传两个素材');
                        return;
                    }
                } else if (formData.screenType === 1) {
                    if (!formData.materialDtoList.length || formData.materialDtoList.length !== 4) {
                        ElMessage.warning('联动需要上传四个素材');
                        return;
                    }
                }
            }

            drawerloading.value = true;
            try {
                await addOrUpdate(baseForm.value.form);
                drawer.value = false;
                ElMessage.success(drawerType.value === '0' ? '新增成功' : '编辑成功');
                searchList({}, { pageNum: 1 });
            } finally {
                drawerloading.value = false;
            }
        }
    });
};

onMounted(async () => {
    searchList(FormData, {});
});
</script>

<style lang="scss" scoped>
.flex-box {
    display: flex;
}
.flex {
    flex: 1;
}
.align-center {
    align-items: center;
}
.search-info {
    // min-width: 1200px;
}
:deep(.large .el-input__inner) {
    width: 580px;
}
:deep(.large .label) {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
::v-deep(.form-input .el-input__prefix-inner) {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    display: inline-block;
    margin-right: 4px;
    &.dot-1 {
        background-color: #22ac4e;
    }
    &.dot-0 {
        background-color: #ffb414;
    }
    &.dot-2 {
        background-color: #e60044;
    }
}

::v-deep(.customer-drawer) {
    width: v-bind(drawerWidth) !important;
    .el-drawer__header {
        .el-drawer__title {
            color: #333;
            font-size: 24px;
            font-weight: 700;
            font-family: 'PingFang SC';
        }
    }
    .el-drawer__body {
        padding: 20px 0 0 24px;
    }
}
</style>
